#!/usr/bin/env python
from google.appengine.ext.webapp import RequestHandler
from google.appengine.api import users
from google.appengine.ext import db

from templates import run, render, redirect, out
from models import UserActions,Friends


class Recent(RequestHandler):
    def get(self):
        #to do: include recent friends too
        user = users.get_current_user()
        ua = UserActions()
        userActions = ua.gql("WHERE email = :1 ORDER BY updated DESC", user)
        
        render(self, 'ajax/recentripples.html', values={'userActions':userActions,'nick':user.nickname()})

class Everyone(RequestHandler):
    def get(self):
        uActions = UserActions.all()
        uActions.order('-updated')
        ua = uActions.fetch(15)
        render(self, 'ajax/allripples.html', values={'allActions': ua })

class Friends(RequestHandler):
    def get(self):
        user = users.get_current_user()
        from models import Friends
        friends = Friends.all()
        friends.filter('email = ', user)
        
        if friends:
            f = []
            for friend in friends:
                fusr = users.User(unicode(friend.email).encode())
                ua = UserActions.all()
                ua.filter('email = ', fusr)
                ua.order('-updated')
                flist = ua.fetch(2)
                
                for fa in flist:
                    f.append({'nickname':fa.nickname, 'email':fa.email, 'action':fa.actions, 'updated':fa.updated})
        else:
            f = None
            
        render(self, 'ajax/friendripples.html', values={'ripples':f})

class History(RequestHandler):
    def get(self):
        user = users.get_current_user()
        ua = UserActions.all()
        ua.filter('email = ', user)
        ua.order('-updated')
        current = ua.fetch(10)
        render(self, 'ajax/ripplehistory.html', values={'actions':current})
        

def main():
    run([('/ajax/recent', Recent), ('/ajax/everyone', Everyone), ('/ajax/friends', Friends), ('/ajax/history', History)])

if __name__ == '__main__': main()